package com.pai4j.message.sender;

import com.pai4j.common.enums.messagequeue.MessageBroadChannelEnum;
import com.pai4j.common.service.messagequeue.producer.MessageQueueProducer;
import com.pai4j.domain.vo.dto.BaseMessageDTO;
import com.pai4j.message.core.sender.AbstractMessageSender;
import com.pai4j.message.model.MessageContext;
import com.pai4j.message.model.SendResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;

import static com.pai4j.common.enums.ResponseCodeEnum.SUCCESS;

/**
 * 消息队列发送器
 * 通过MQ发送消息（异步）
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
@Component
@ConditionalOnBean(MessageQueueProducer.class)
public class MessageQueueSender extends AbstractMessageSender {

    @Autowired(required = false)
    private MessageQueueProducer<BaseMessageDTO, Long> messageQueueProducer;

    @PostConstruct
    public void register() {
        com.pai4j.message.factory.MessageSenderFactory.register(this);
        log.info("MessageQueueSender已注册");
    }

    @Override
    public String getChannel() {
        return "message-queue";
    }

    @Override
    protected SendResult doSend(MessageContext context) {
        if (!validateContext(context)) {
            return SendResult.failure("INVALID_CONTEXT", "消息上下文验证失败", getChannel());
        }

        if (messageQueueProducer == null) {
            log.error("MessageQueueProducer未注入，无法发送消息");
            return SendResult.failure("NO_PRODUCER", "消息队列生产者未配置", getChannel());
        }

        try {
            BaseMessageDTO messageDTO = context.getMessageDTO();
            
            // 发送到MQ
           messageQueueProducer.broadSend(
                    MessageBroadChannelEnum.QUEUE_USER_MESSAGE, 
                    messageDTO
            );

            log.info("消息发送到MQ成功:category={}, type={}",
                    messageDTO.getCategory(), messageDTO.getType());

            return SendResult.success(messageDTO.getTaskId(), getChannel());

        } catch (Exception e) {
            log.error("消息发送到MQ失败: error={}", e.getMessage(), e);
            return SendResult.failure("SEND_ERROR", e.getMessage(), getChannel());
        }
    }

    @Override
    public boolean isAvailable() {
        return messageQueueProducer != null;
    }

    @Override
    public int getPriority() {
        return 10; // 高优先级
    }
}

